//引入模块
const express = require("express");
//引入mysql连接池对象
const query = require("../util/query.js");
const JWT = require('../util/token.js');

//创建空路由器
let router = express.Router();
//============================================
// 订单管理模块
//===============================================
// 1 创建订单 POST /order/create
// 参数名	参数说明	备注
// address_id	收货地址id
// remark	备注信息
// productList	购买商品数组,如：
//	[{"product_id":"1","count":5,"price":129},
//   {"product_id":"2","count":23,"price":222}]  这里的product_id是指商品id
router.post("/create", async (req, res) => {
  //验证用户Token 请求头中携带Token  req.headers.authorization=
  let user = JWT.getUser(req, res);
  if (user == null) return; 

  //以下代码没有考虑数据库的事务操作，需要进一步完善的....
  try {
    //1获取收货人地址编号数据
    let { address_id ,remark , productList } = req.body;
    address_id = parseInt(address_id);
    if (!address_id) throw new Error("收货人地址id不能为空");  
    if (!productList) throw new Error("购买商品不能为空");     
    
		let orderProduct = null;
		if(typeof(productList)==="string"){
			orderProduct = JSON.parse(productList); //传递过来的订单商品列表			
		}
		
		if(typeof(productList)==="object"){
			orderProduct = productList;
		}
		
		if(orderProduct===null) throw new Error("购买商品列表数据格式不正确");  
		
    // 创建订单  （主表）
    let order = {};
    order.user_id = user.id;
    order.address_id = address_id;
    order.status = 0; // -1 取消  0 未付款  1 付款
    order.remark = remark;

    sql = "INSERT INTO lz_order SET ?";
    result = await query(sql, [order]);
    let order_id = result.insertId;  //获取新订单的编号
    
    //有了新订单的编号，才能插入订单项数据 （ 从表 ）
    for (let i = 0; i < orderProduct.length; i++) {
      let product = { ...orderProduct[i] , order_id }; //订单商品记录添加订单编号值
      sql = "INSERT INTO lz_order_detail SET ?";
      await query(sql, [product]);
    }
    return res.send({ code: 1, msg: `创建订单成功` });

  } catch (error) {
    res.send({ code: -1, msg: error.message }); 
  }
});

//===================================================
// 2 查询订单列表 GET /order/list （返回数据包含订单的商品明细）
// 参数名	参数说明	备注
// 无参数
router.get("/list", async (req, res) => {
  //验证用户Token 请求头中携带Token  req.headers.authorization=
  let user = JWT.getUser(req, res);
  if (user == null) return; 

  try {
    //获取当前用户的订单
    let sql = `select id,user_id,receiver,phone,address,status,order_time,remark from v_order where user_id = ${user.id} `;
    let result = await query(sql);
    if (result.length == 0) {
			res.send({ code: 1, msg: `订单查询成功`, data:[] });
			return;
		}
    let orderList = result;

    // 获取每个订单的商品列表
    for (let i = 0; i < orderList.length; i++) {
      let order = orderList[i];
      let sql = `select product_id,count,price,product_name,product_pic from v_order_detail where order_id = ${order.id}`;
      let detailList = await query(sql);
      order.detailList = detailList; //添加该订单的商品列表
    }

    let data = orderList;
    res.send({ code: 1, msg: `订单查询成功`, data });
  } catch (error) {
    res.send({ code: -1, msg: error.message }); 
  }
});


//===================================================
// 3 查询订单详情 GET /order/detail
// 参数名	参数说明	备注
// id	订单id
router.get("/detail", async (req, res) => {
  //验证用户Token 请求头中携带Token  req.headers.authorization=
  let user = JWT.getUser(req, res);
  if (user == null) return; 


  try {
    //请求参数
    let id = parseInt(req.query.id) || 0;
    if (!id) throw new Error("查询的订单编号不能为空");

    //获取当前用户的订单头数据
    let sql = `select id,user_id,receiver,phone,address,status,order_time,remark from v_order where user_id = ${user.id} AND id = ${id}`;
    let result = await query(sql);
    if (result.length != 1) throw new Error("当前用户没有订单,或订单号重复了！");

    //当前用户有订单（只有1个)，则继续处理
    let order = result[0];

    // 继续获取该订单的商品列表数据
    sql = `select product_id,count,price,product_name,product_pic from v_order_detail where order_id = ${order.id}`;
    let detailList = await query(sql);
    order.detailList = detailList; //添加该订单的商品明细   

    let data = order;
    res.send({ code: 1, msg: `订单查询成功`, data });
  } catch (error) {
    res.send({ code: -1, msg: error.message }); 
  }
});

//===================================================
// 4 取消订单 POST  /order/cancel
// 参数名	参数说明	备注
// id	订单id
router.post("/cancel", async (req, res) => {
  //验证用户Token 请求头中携带Token  req.headers.authorization=
  let user = JWT.getUser(req, res);
  if (user == null) return; 

  try {
    //请求参数
    let id = parseInt(req.body.id) || 0; //POST从body中取参数
    if (!id) throw new Error("取消的订单编号不能为空");

    //获取当前用户的订单  (未取消的订单)
    let sql = `select * from lz_order where user_id = ${user.id} AND id = ${id} AND status >=0 `;
    let result = await query(sql);
    if (result.length != 1)
      throw new Error("当前用户没有订单或订单已取消！");

    //当前用户有一条订单，则继续处理
    let order = result[0];    

    //设置订单的取消标志值 -1已取消 0未付款 1已付款 
    sql = `update lz_order set status = -1 where id=${order.id}`;
    await query(sql);
    res.send({ code: 1, msg: `订单取消成功` });
  } catch (error) {
    res.send({ code: -1, msg: error.message }); 
  }
});


//===================================================
// 5 删除订单 POST  /order/delete
// 参数名	参数说明	备注
// id	订单id
router.post("/delete", async (req, res) => {
  //验证用户Token 请求头中携带Token  req.headers.authorization=
  let user = JWT.getUser(req, res);
  if (user == null) return; 

  try {
    //请求参数
    let id = parseInt(req.body.id) || 0; //POST从body中取参数
    if (!id) throw new Error("订单编号不能为空");
		
		//删除订单 项
    let sql = `DELETE FROM lz_order_detail WHERE order_id = ${id} `;    
    await query(sql);
    //删除订单 头
    sql = `DELETE FROM lz_order WHERE id = ${id} `;    
    await query(sql);
		
    res.send({ code: 1, msg: `订单删除成功` });
  } catch (error) {
    res.send({ code: -1, msg: error.message }); 
  }
});


/* 管理员admin使用的接口 */
// 增加   管理员没有增加订单功能

// 删除   和前端相同（前端删除订单只是根据订单id删除的）
// 5 删除订单 POST  /order/delete
// 参数名	id	订单id 

// 更改   管理员没有更改订单功能

// 分页查询
//===================================================
// 查询订单列表 GET /order/admin/page （返回数据中不包含订单的商品明细）
// 参数名	参数说明	备注
// 页号   pageIndex
// 页大小 pageSize 
// 搜索 keyword (在收货人或地址中匹配)
// 排序 orderBy
router.get("/admin/page", async (req, res) => {
	//验证用户Token 请求头中携带Token  req.headers.authorization=
	let user = JWT.getUser(req, res);
	if (user == null) return; 
	
  try {
    //获取数据
    let { pageIndex, pageSize, keyword , orderBy } = req.query;
		//console.log(req.query);
    keyword = keyword || "";
		orderBy = orderBy || " id ";
		
    //获取数据：起始页码，从1开始
    pageIndex = parseInt(pageIndex);
    pageIndex = pageIndex ? pageIndex : 1;
    //获取数据：每页大小
    pageSize = parseInt(pageSize);
    pageSize = pageSize ? pageSize : 2147483647;  //缺省则不分页
    //计算开始查询的值start
    let start = (pageIndex - 1) * pageSize;

    //建sql语句  
    let sql1 = `select count(*) as count from v_order where 1=1 `;
		let sql2 = `SELECT * FROM v_order  where 1=1 `;
		if(keyword){
			const sql_Like = ` AND ( receiver LIKE '%${keyword}%' OR address LIKE '%${keyword}%') `;
			sql1 += sql_Like;
			sql2 += sql_Like
		} 
		if(orderBy) sql2 += ` ORDER BY ${orderBy} `
		sql2 += ` LIMIT ${start},${pageSize}`			
    let sql = `${sql1} ; ${sql2}`;
    
		//console.log(sql)  //调试输出
    //执行Query
    let result = await query(sql);
    //处理返回数据，（返回记录数量是0也是一种成功），响应对象
    let recordTotal = result[0][0]["count"]; //获取记录总数，第1个SQL语句的执行结果
    let pageTotal = Math.floor(recordTotal / pageSize) + 1; //计算总页数
    let data = result[1];//第2个SQL语句的执行结果     
    res.send({
      code: 1,
      msg: "获取成功",
      recordTotal, //总记录数
      pageIndex,  //页号
      pageSize, //每页大小
      pageTotal,  //总页数
      data
    });
  } catch (error) {
    res.send({ code: -1, msg: error.message });
  }
});


// 查询订单详情 GET /order/admin/detail (可以查询不是当前用户的订单)
// 参数名	参数说明	备注
// id	订单id
router.get("/detail", async (req, res) => {
  //验证用户Token 请求头中携带Token  req.headers.authorization=
  let user = JWT.getUser(req, res);
  if (user == null) return; 


  try {
    //请求参数
    let id = parseInt(req.query.id) || 0;
    if (!id) throw new Error("查询的订单编号不能为空");

    //获取订单头数据
    let sql = `select id,user_id,receiver,phone,address,status,order_time,remark from v_order where id = ${id}`;
    let result = await query(sql);
    if (result.length != 1) throw new Error("订单不存在,或订单重复错误！");

    //有订单（只有1个)，则继续处理
    let order = result[0];

    // 继续获取该订单的商品列表数据
    sql = `select product_id,count,price,product_name,product_pic from v_order_detail where order_id = ${order.id}`;
    let detailList = await query(sql);
    order.detailList = detailList; //添加该订单的商品明细   

    let data = order;
    res.send({ code: 1, msg: `订单查询成功`, data });
  } catch (error) {
    res.send({ code: -1, msg: error.message }); 
  }
});

//===============================================
//导出路由器
module.exports = router;